#include <fstream>
#include <iostream>
#include "TestQuery.h"

ifstream& open_file(ifstream&, const string&);
ifstream& open_file(ifstream&, const string&);
string make_plural(size_t, const string&, const string&);
void print_results(const set<TextQuery::line_no> &, const string &, const TextQuery &);

using namespace std;

int main(int argc, char ** argv)
{
	ifstream inFile;
/*
	if(argc < 2 || !open_file(inFile, argv[1]))
	{
		cerr << "" << endl;
		return EXIT_FAILURE;
	}
	*/
	open_file(inFile, "D:\\Own Projects\\Codeplex\\CppPrimer\\Debug\\1.txt");
	TextQuery tq;
	tq.read_file(inFile);
	while(true)
	{
		cout << "Enter word to look for, or q to quit:" << endl;
		string s;
		cin >> s;
		if(!cin || s == "q")
			break;
		set<TextQuery::line_no> locs = tq.run_query(s);
		print_results(locs, s, tq);
	}

	return 0;
}

ifstream& open_file(ifstream &inFileStream, const string &file)
{
	inFileStream.close();
	inFileStream.clear();
	inFileStream.open(file.c_str());
	return inFileStream;
}

void print_results(const set<TextQuery::line_no> &locs, const string &sought, const TextQuery &file)
{
	typedef set<TextQuery::line_no> line_nums;
	line_nums::size_type size = locs.size();
	cout << endl << sought << " occurs " << size << " " << make_plural(size, "time", "s") << endl;

	line_nums::const_iterator it = locs.begin();
	for( ; it != locs.end(); ++it)
	{
		cout << "\t(line " << (*it) + 1 << ") " << file.text_line(*it) << endl;
	}
}

string make_plural(size_t ctr, const string &word, const string &ending)
{
	return (ctr == 1) ? word : word + ending;
}